package com.xique.door.service.impl.wechat;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.json.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.BaseUserV1;
import com.xique.door.bean.domain.WxUser;
import com.xique.door.service.IBaseUserService;
import com.xique.door.service.IWxUserService;
import com.xique.door.service.wechat.IWechatGzhNotifyService;
import com.xique.door.util.WechatUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: xq-cloud
 * @ClassName IWechatGzhNotifyServiceImpl
 * @description:
 * @author: HdongSun
 * @create: 2022-08-22 15:16
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class WechatGzhNotifyServiceImpl implements IWechatGzhNotifyService {

    @Value("${wx.gzh.appId}")
    private String appId;

    @Value("${wx.gzh.secret}")
    private String secret;

    private final WechatUtils wechatUtils;

    private final IWxUserService wxUserService;

    private final IBaseUserService baseUserService;

    @Override
    public AjaxResult delaySubscribeEvent(String fromUserName) {
        JSONObject jsonObject = wechatUtils.getGzhUserInfo(appId, secret, fromUserName);

        String openId = jsonObject.getStr("openid");
        if (StrUtil.isEmpty(openId)) {
            return AjaxResult.error("处理失败");
        }
        WxUser search = new WxUser();
        search.setOpenId(openId);
        List<WxUser> list = wxUserService.getList(search);

        WxUser wxUser = OrikaUtil.convert(jsonObject, WxUser.class);
        wxUser.setOpenId(jsonObject.getStr("openid"));
        wxUser.setUnionId(jsonObject.getStr("unionid"));
        wxUser.setSubscribeTime(jsonObject.getLong("subscribe_time"));
        wxUser.setSubscribeScene(jsonObject.getStr("subscribe_scene"));
        wxUser.setTagidList(jsonObject.getStr("tagid_list"));
        if (CollUtil.isEmpty(list)) {
            wxUserService.save(wxUser);
        } else {
            wxUser.setId(list.get(0).getId());
            wxUserService.updateById(wxUser);
        }

        // TODO 更新base_user表用户数据
        BaseUserV1 baseUser = baseUserService.selectBaseUserV1ByUnionId(wxUser.getUnionId());
        if (ObjectUtil.isNotEmpty(baseUser) && StrUtil.isEmpty(baseUser.getWechatGzOpenid())) {
            BaseUserV1 update = new BaseUserV1();
            update.setId(baseUser.getId());
            update.setWechatUnionid(wxUser.getUnionId());
            update.setWechatGzOpenid(wxUser.getOpenId());
            baseUserService.updateById(update);
        }

        log.info("wxUser:{}", wxUser);
        return AjaxResult.success();
    }
}
